const fs=require('fs');
const postcss=require('postcss');
const autoprefixer=require('autoprefixer');
import { getWorkPath,getTragetPath } from '../../env'

export async function compileWxss(moduleDeps){
    let cssMergeCode=await getCompileCssCode({
        path:'app',
        moduleId:''
    });
    const distPath=getTragetPath();
    for(const path in moduleDeps){
        cssMergeCode+=await getCompileCssCode({
            path,
            moduleId:moduleDeps[path].moduleId,
        })
    }

    fs.writeFileSync(`${distPath}/style.css`,cssMergeCode,'utf-8');

}

async function getCompileCssCode(opts){
    const {path,moduleId}=opts;
    const workPath=getWorkPath();
    const wxssFileFullPath=`${workPath}/${path}.wxss`;
    const wxssCode=fs.readFileSync(wxssFileFullPath,'utf-8');
    const ast=postcss.parse(wxssCode);
    ast.walk((node)=>{
        if(node.type==='rule'){
            node.walkDecls((decl)=>{
                decl.value=decl.value.replace(/rpx/g,'rem')
            })
        }
    })
    const tranUnitCode=ast.toResult().css;
    const result=await transCode(tranUnitCode,moduleId);
    return result;
}

function transCode(code,moduleId){
    return new Promise((resolve,reject)=>{
        postcss([
            addScopeId({moduleId}),
            autoprefixer({overrideBrowserslist: ['cover 99.5%']})
        ])
        .process(code,{from:undefined})
        .then(result=>{
            resolve(result.css+'\n');
        });
    });
}

function addScopeId(opts){
    const {moduleId}=opts;
    function func(){
        return {
            postcssPlugin:'addScopeId',
            prepare(){
                return {
                    OnceExit(root){
                        root.walkRules((rule)=>{
                            if(!moduleId){
                                return;
                            }
                            //css动画
                            if(/%/.test(rule.selector)){
                                return;
                            }
                            
                            /* 
                                伪类::placeholder.anima-view::after{
                                    content:'';
                                    width:50rpx;
                                    height:50rpx;
                                    background-color:red;
                                } 
                            */
                            if(/::/.test(rule.selector)){
                                rule.selector=rule.selector.replace(/::/,`[data-v-${moduleId}]::`);
                                return;
                            }

                            rule.selector+=`[data-v-${moduleId}]`;
                        })
                    }
                }
            }
        }
    }
    func.postcss=true;
    return func;
}

